package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class TsLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object tsLoginAspect(ProceedingJoinPoint joinPoint, TsLogin tsLogin) throws Throwable {
        //获取到token！核心控制器；映射器；适配器；视图解析器！

        //获取请求上下文对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;

        //获取请求对象
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");

        //  要求必须要登录！
        if (tsLogin.required()) {
            // 判断token是否为空
            if (StringUtils.isEmpty(token)) {
                // 抛出异常，给页面提示，跳转到登录页面！
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            //  构建Redis键名,可能有token,需要根据token去获取用户信息，看用户信息是否真正存在！ key 唯一； key=user:token:info value={"name":"admin"}
            String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            // 从Redis中获取用户信息
            UserInfo userInfo = (UserInfo) this.redisTemplate.opsForValue().get(key);
            //  判断当前用户是否为空
            if (null == userInfo) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
        }
        try {
            //否则，不需要登录！我们需要存储用户Id到本地线程！便于其他微服务快速获取用户Id！
            if (!StringUtils.isEmpty(token)) {
                String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) this.redisTemplate.opsForValue().get(key);
                if (null != userInfo) {
                    //  存储用户Id到本地线程
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            //  执行目标方法
            return joinPoint.proceed();

        } catch (GuiguException e) {
            throw new RuntimeException(e);
        } finally {
            //  删除本地内存信息！
            AuthContextHolder.removeUserId();
        }
    }
}
